package com.tank.music;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import java.io.File;

public class SoundEffect {

    private Clip clip;

    // 构造方法，加载声音文件
    public SoundEffect(String soundFileName) {
        try {
            File soundFile = new File(soundFileName);
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundFile);
            clip = AudioSystem.getClip();
            clip.open(audioInputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 播放声音
    public void play() {
        if (clip != null) {
            clip.setFramePosition(0); // 重置到声音文件的开始
            clip.start(); // 开始播放
        }
    }

    // 停止播放
    public void stop() {
        if (clip != null && clip.isRunning()) {
            clip.stop(); // 停止播放
        }
    }

    // 释放资源
    public void close() {
        if (clip != null) {
            clip.close();
        }
    }
}

